package com.hexiang.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author h01463
 * @version 1.0
 * @date 2024/8/7 11:38
 */
@Configuration
public class CustomBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        Map<Object, Object> result = new HashMap<>(2);
        String msg = null;
        Integer code = 0;
        if (e instanceof FlowException) {
            msg = "系统繁忙";
            code = 1;
        } else if (e instanceof BlockException) {
            msg = "系统繁忙";
            code = 2;
        } else if (e instanceof ParamFlowException) {
            msg = "系统繁忙";
            code = 3;
        } else if (e instanceof SystemBlockException) {
            msg = "系统繁忙";
            code = 4;
        }
        result.put("code", code);
        result.put("msg", msg);
        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.writeValue(response.getWriter(), result);
    }
}
